import React, {Component} from 'react';
import {StyleSheet, Text, View, TextInput} from 'react-native';
import AsyncStorage from '@react-native-community/async-storage';

export default class AsyncStorageDemoPage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      showText: ''
    }
  }
  // 存储
  doSave() {
    AsyncStorage.setItem('userId', this.value) // AsyncStorage的执行方式会返回一个Promise，可以使用catch捕获异常
      .catch(error => {
        error && console.log(error.toString())
      })
  }
  // 删除
  doRemove() {
    AsyncStorage.removeItem('userId', error => { // 也可以使用回调函数捕获异常
      error && console.log(error.toString())
    });
  }
  // 获取
  async doGet() { // 如果使用 async和await的形式，可以用try catch的方式捕获异常
    try {
      const userId = await AsyncStorage.getItem('userId');
      this.setState({
        showText: userId
      });
    } catch (error) {
      error && console.log(error.toString())
    }
  }

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>AsyncStorage示例</Text>
        <TextInput
          style={{width: 200, height: 40, borderColor: 'gray', borderWidth: 1}}
          onChangeText={text => {
            this.value = text
          }}
        />
        <View style={{alignSelf: 'stretch', height: 50, flexDirection: 'row', justifyContent: 'space-around'}}>
          <Text
            onPress={() => {
              this.doSave()
            }}
          >存储</Text>
          <Text
            onPress={() => {
              this.doRemove()
            }}
          >删除</Text>
          <Text
            onPress={() => {
              this.doGet();
            }}
          >读取</Text>
        </View>
        <Text>{this.state.showText}</Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  }
});
